package com.aiapphub.BaseCode.handler.mybatisPlus;

import com.aiapphub.BaseCode.utils.EncryptUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.*;

@Component
public class StringEncryptTypeHandler extends BaseTypeHandler<String> { // 泛型改为String

    private static String aesKey;
    private static String aesIv;

    @Value("${encrypt.aes.key}")
    public void setAesKey(String key) {
        aesKey = key;
    }

    @Value("${encrypt.aes.iv}")
    public void setAesIv(String iv) {
        aesIv = iv;
    }

    //---------------------- 插入数据时的加密处理 ----------------------
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, 
                                    String parameter, JdbcType jdbcType) throws SQLException {
        try {
            String encrypted = EncryptUtil.encrypt(parameter, aesKey, aesIv);
            ps.setString(i, encrypted);
        } catch (Exception e) {
            throw new SQLException("字段加密失败，参数位置：" + i, e);
        }
    }

    //---------------------- 查询结果时的解密处理 ----------------------
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String encrypted = rs.getString(columnName);
        return decryptToString(encrypted);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String encrypted = rs.getString(columnIndex);
        return decryptToString(encrypted);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String encrypted = cs.getString(columnIndex);
        return decryptToString(encrypted);
    }

    //---------------------- 统一解密方法 ----------------------
    private String decryptToString(String encrypted) throws SQLException {
        if (encrypted == null) return null;
        try {
            return EncryptUtil.decrypt(encrypted, aesKey, aesIv);
        } catch (Exception e) {
            throw new SQLException("字段解密失败，加密值前8位：" + encrypted.substring(0, Math.min(8, encrypted.length())), e);
        }
    }
}